
package com.example.ice.coursetable;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureFailure;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.Face;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.ExifInterface;
import android.media.Image;
import android.media.ImageReader;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.ice.coursetable.flashstrategy.AutoStrategy;
import com.example.ice.coursetable.flashstrategy.CloseStrategy;
import com.example.ice.coursetable.flashstrategy.FlashStrategy;
import com.example.ice.coursetable.wbstrategy.AutoWBStrategy;
import com.example.ice.coursetable.wbstrategy.CloudyWBStrategy;
import com.example.ice.coursetable.wbstrategy.DaylightWBStrategy;
import com.example.ice.coursetable.wbstrategy.FluoreWBStrategy;
import com.example.ice.coursetable.wbstrategy.IncandeWBStrategy;
import com.example.ice.coursetable.flashstrategy.KeepOpenStrategy;
import com.example.ice.coursetable.flashstrategy.OpenStrategy;
import com.example.ice.coursetable.wbstrategy.ShadeWBStrategy;
import com.example.ice.coursetable.wbstrategy.TwilightWBStrategy;
import com.example.ice.coursetable.wbstrategy.WarmWBStrategy;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;

public class CameraActivity extends AppCompatActivity implements View.OnClickListener {
    private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
    private static final String TAG = "CameraActivity";

    private static void Log(String message) {
        Log.i(CameraActivity.class.getName(), message);
    }

    ///为了使照片竖直显示
    static {
        ORIENTATIONS.append(Surface.ROTATION_0, 90);
        ORIENTATIONS.append(Surface.ROTATION_90, 0);
        ORIENTATIONS.append(Surface.ROTATION_180, 270);
        ORIENTATIONS.append(Surface.ROTATION_270, 180);
    }

    private View mFlashLayout, mSettingLayout, mCameraLayout, mSwitchLayou, mVoideLayout, mawbLayout;
    private TextView tv_flashStatus, tv_flashClose, tv_flashOpen, tv_flashKeepOpen,
            tv_flashAuto, tv_time, tv_cameraOpen, tv_viodeOpen, tv_awb, textView;
    private ImageView iv_thumb, iv_changeCamera, iv_flash, iv_wb_auto, iv_wb_cloudy,
            iv_wb_daylight, iv_wb_fluore, iv_wb_incande, iv_wb_shade, iv_wb_twilight, iv_wb_warm;

    private int mCameraID;
    private ImageReader mImageReader;
    private CameraDevice mCameraDevice;//摄像头设备
    private CameraManager mCameraManager;
    private CameraCaptureSession mCameraCaptureSession;
    private CameraCaptureSession.StateCallback mSessionStateCallback;

    private AutoFitTextureView mTextureView;//相机预览
    private AutoFitTextureView mdrView;//用于标注人脸
    private CameraDevice.StateCallback mCameraDeviceStateCallback;
    private CameraCaptureSession.CaptureCallback mSessionCaptureCallback;
    private CaptureRequest.Builder mPreviewCaptureRequest;
    private CaptureRequest.Builder mRecorderCaptureRequest;
    private MediaRecorder mMediaRecorder;
    private String mCurrentSelectCamera;
    private Handler mChildHandler;
    private Handler mainHandler;

    private Size cameraSize;
    private Paint pb;
    private int[] faceDetectModes;

    public final int FLASH_ON = 1;
    public final int FLASH_OFF = 2;

    public final int BACK_CAMERA = 0; //后置摄像头的CameraId
    public final int FRONT_CAMERA = 1;

    private static final int REQUSET_CAMERA_PERMISSION = 1;

    //文件名
    private String jpegName;
    private String voideName;

    private File voidefile;



    //图片扩展信息
    private ExifInterface exif;


    //权限申请
    private static final String[] permission = new String[]{
            //相机、读、写、录音权限、网络、wifi、定位
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
    };

    //延迟时间记录
    private EditText ed_time;
    private String delayName;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;




    //定位信息
    private LocationManager locationManager;
    private GpsStatus gpsstatus;


    public boolean checkPermission() {
        if (isPermissionGranted()) {
            return true;
        } else {
            ActivityCompat.requestPermissions(this, permission, REQUSET_CAMERA_PERMISSION);
            return false;
        }
    }

    public boolean isPermissionGranted() {
        if (Build.VERSION.SDK_INT >= 23) {
            for (int i = 0; i < permission.length; i++) {
                int checkPermission = ContextCompat.checkSelfPermission(this, permission[i]);//动态申请权限
                if (checkPermission != PackageManager.PERMISSION_GRANTED) {//已获得权限
                    return false;
                }
            }
            return true;
        } else {
            return true;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);//隐藏标题栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//隐藏状态栏
        setContentView(R.layout.activity_camera);
        checkPermission();
        initView();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1) {
            for (int grantResult : grantResults) {
                if (grantResult != PERMISSION_GRANTED) {
                    Toast.makeText(this, "对不起，没有权限，无法正常使用相机", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
//            initView();
        }
    }


    private void initView() {
        mSettingLayout = findViewById(R.id.layout_setting);
        mCameraLayout = findViewById(R.id.layout_camera);
        mVoideLayout = findViewById(R.id.layout_voide);
        mSwitchLayou = findViewById(R.id.layout_switch);
        mawbLayout = findViewById(R.id.layout_awb);

        iv_flash = findViewById(R.id.iv_flash);
        iv_thumb = findViewById(R.id.iv_thumb);
        tv_flashStatus = findViewById(R.id.tv_flash_status);

        mTextureView = findViewById(R.id.textureview);
        mdrView = findViewById(R.id.drView);
        textView = findViewById(R.id.textView);

        iv_changeCamera = findViewById(R.id.iv_change);

        tv_cameraOpen = findViewById(R.id.tv_camera_open);
        tv_viodeOpen = findViewById(R.id.tv_viode_open);
        tv_awb = findViewById(R.id.tv_awb);

        mFlashLayout = findViewById(R.id.layout_flash_text);
        tv_flashAuto = mFlashLayout.findViewById(R.id.tv_flash_auto);
        tv_flashClose = mFlashLayout.findViewById(R.id.tv_flash_close);
        tv_flashKeepOpen = mFlashLayout.findViewById(R.id.tv_flash_keep_open);
        tv_flashOpen = mFlashLayout.findViewById(R.id.tv_flash_open);

        iv_wb_auto = findViewById(R.id.iv_wb_auto);
        iv_wb_cloudy = findViewById(R.id.iv_wb_cloudy);
        iv_wb_daylight = findViewById(R.id.iv_wb_daylight);
        iv_wb_fluore = findViewById(R.id.iv_wb_fluore);
        iv_wb_incande = findViewById(R.id.iv_wb_incande);
        iv_wb_shade = findViewById(R.id.iv_wb_shade);
        iv_wb_twilight = findViewById(R.id.iv_wb_twilight);
        iv_wb_warm = findViewById(R.id.iv_wb_warm);

        //隐藏背景颜色，以免标注人脸时挡住预览画面
        mdrView.setAlpha(0.9f);

        tv_flashAuto.setOnClickListener(this);
        tv_flashClose.setOnClickListener(this);
        tv_flashKeepOpen.setOnClickListener(this);
        tv_flashOpen.setOnClickListener(this);

        iv_wb_auto.setOnClickListener(this);
        iv_wb_cloudy.setOnClickListener(this);
        iv_wb_daylight.setOnClickListener(this);
        iv_wb_fluore.setOnClickListener(this);
        iv_wb_incande.setOnClickListener(this);
        iv_wb_shade.setOnClickListener(this);
        iv_wb_twilight.setOnClickListener(this);
        iv_wb_warm.setOnClickListener(this);

        //延时记录
//        tv_time = findViewById(R.id.tv_time);
        ed_time = findViewById(R.id.ed_time);
        sharedPreferences = getSharedPreferences("delayTime", Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();

        String time = sharedPreferences.getString("time", "");
        if (time != null) {
            ed_time.setText(time);
        }


        //拍照点击事件
        findViewById(R.id.btn_control).setOnClickListener(v -> {
            isTime();
//            isSleep();
            shutter(R.raw.suond);
            takePicture();
        });

        //录像开始点击事件
        findViewById(R.id.btn_state).setOnClickListener(v -> {
            shutter(R.raw.stop);
            Animation anim = AnimationUtils.loadAnimation(this, R.anim.flash_in);
            mFlashLayout.setAnimation(anim);
            findViewById(R.id.btn_stop).setVisibility(View.VISIBLE);
            anim = AnimationUtils.loadAnimation(this, R.anim.flash_out);
            mFlashLayout.setAnimation(anim);
            findViewById(R.id.btn_state).setVisibility(View.GONE);

            config();
            startRecorder();

        });

        //录像停止点击事件
        findViewById(R.id.btn_stop).setOnClickListener(v -> {
            shutter(R.raw.state);
            Animation anim = AnimationUtils.loadAnimation(this, R.anim.flash_in);
            mFlashLayout.setAnimation(anim);
            findViewById(R.id.btn_state).setVisibility(View.VISIBLE);
            anim = AnimationUtils.loadAnimation(this, R.anim.flash_out);
            mFlashLayout.setAnimation(anim);
            findViewById(R.id.btn_stop).setVisibility(View.GONE);
            stopRecorder();
            requestPreve();

        });


        //点击闪光灯图标
        iv_flash.setOnClickListener(v -> {
            Animation anim = AnimationUtils.loadAnimation(this, R.anim.flash_in);
            mFlashLayout.setAnimation(anim);
            mFlashLayout.setVisibility(View.VISIBLE);
        });

        //拍照录屏切换
        tv_cameraOpen.setOnClickListener(v -> {
            Log.d(TAG, "拍照");
            Animation anim = AnimationUtils.loadAnimation(this, R.anim.flash_in);
            mFlashLayout.setAnimation(anim);
            mCameraLayout.setVisibility(View.VISIBLE);
            findViewById(R.id.btn_control).setVisibility(View.VISIBLE);
            anim = AnimationUtils.loadAnimation(this, R.anim.flash_out);
            mFlashLayout.setAnimation(anim);
            mawbLayout.setVisibility(View.GONE);
            findViewById(R.id.btn_state).setVisibility(View.GONE);
            findViewById(R.id.btn_stop).setVisibility(View.GONE);
            tv_viodeOpen.setBackground(null);
            tv_awb.setBackground(null);
            tv_cameraOpen.setBackground(getResources().getDrawable(R.drawable.flash_text_shape));
        });

        tv_viodeOpen.setOnClickListener(v -> {
            Log.d(TAG, "录像");
            Animation anim = AnimationUtils.loadAnimation(this, R.anim.flash_in);
            mFlashLayout.setAnimation(anim);
            mCameraLayout.setVisibility(View.VISIBLE);
            findViewById(R.id.btn_state).setVisibility(View.VISIBLE);
            anim = AnimationUtils.loadAnimation(this, R.anim.flash_out);
            mFlashLayout.setAnimation(anim);
            findViewById(R.id.btn_control).setVisibility(View.GONE);
            mawbLayout.setVisibility(View.GONE);
            tv_cameraOpen.setBackground(null);
            tv_awb.setBackground(null);
            tv_viodeOpen.setBackground(getResources().getDrawable(R.drawable.flash_text_shape));

        });

        tv_awb.setOnClickListener(v -> {
            Log.d(TAG, "白平衡");
            Animation anim = AnimationUtils.loadAnimation(this, R.anim.flash_in);
            mFlashLayout.setAnimation(anim);
            mawbLayout.setVisibility(View.VISIBLE);
            anim = AnimationUtils.loadAnimation(this, R.anim.flash_out);
            mFlashLayout.setAnimation(anim);
            mCameraLayout.setVisibility(View.GONE);
            tv_cameraOpen.setBackground(null);
            tv_viodeOpen.setBackground(null);
            tv_awb.setBackground(getResources().getDrawable(R.drawable.flash_text_shape));
        });

        //查看照片
        iv_thumb.setOnClickListener(v -> {
            //        Log.d(TAG,"打开相册");
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setType("vnd.android.cursor.dir/image");
//        intent.setDataAndType(Uri.fromFile(mFile),"image/*");
            startActivity(intent);

//            File file=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)+"/"+jpegName);
//            Intent it =new Intent(Intent.ACTION_VIEW);
//            Uri mUri = Uri.parse("file://"+file.getPath());
//            it.setDataAndType(mUri, "image/*");
//            startActivity(it);
        });

        //更换摄像头
        iv_changeCamera.setOnClickListener(v -> changeCamera());

        mTextureView = findViewById(R.id.textureview);
        initChildHandler();
        initTextureViewStateListener();
        initMediaRecorder();
        initCameraDeviceStateCallback();
        initSessionStateCallback();
        initSessionCaptureCallback();
        initTakePhoto();

    }


    //延时数字记录
    private void isTime() {
        delayName = ed_time.getText().toString().trim();
        if (!delayName.equals(null) || !delayName.equals("")) {
            editor.putString("time", delayName);
            editor.apply();
            if (delayName == null || delayName.equals("")) {
                return;
            } else {
                int i = Integer.parseInt(delayName);
//                tv_time.setText(delayName);
                new Sleep(i).run();
            }


        }

    }


    //拍照声音
    private MediaPlayer mediaPlayer;
    private AudioManager audioManager;

    private void shutter(int tem) {
        audioManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
        mediaPlayer = MediaPlayer.create(this, tem);
//        mediaPlayer.setLooping(true);//循环播放声音
        mediaPlayer.start();

    }

    @SuppressLint({"MissingPermission"})
    private void changeCamera() {
        try {
            //先关闭之前的摄像头
            if (mCameraDevice != null) {
                mCameraDevice.close();
                mCameraDevice = null;
            }
            mCameraID ^= 1;
            mCameraManager.openCamera(mCameraID + "", mCameraDeviceStateCallback, mChildHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("MissingPermission")
    private void requestPreve() {
        try {
            //先关闭之前的摄像头
            if (mCameraDevice != null) {
                mCameraDevice.close();
                mCameraDevice = null;
            }
            mCameraManager.openCamera(mCameraID + "", mCameraDeviceStateCallback, mChildHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }


    /*
     * 保存文件，文件名为当前日期
     */
    @SuppressLint("NewApi")
    public void saveBitmap(Bitmap bitmap, String bitName) {
        String fileName;
        File file;
        if (Build.BRAND.equals("Xiaomi")) { // 小米手机
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + bitName;
        } else { // Meizu 、Oppo
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/" + bitName;
        }
        file = new File(fileName);
        if (file.exists()) {
            file.delete();
        }
//        FileOutputStream out;

//        GSPlocation();

        try {
            FileOutputStream out = new FileOutputStream(file);
            // 格式为 JPEG，照相机拍出的图片为JPEG格式的，PNG格式的不能显示在相册中
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)) {
                out.flush();
                out.close();
// 插入图库
                MediaStore.Images.Media.insertImage(this.getContentResolver(), file.getAbsolutePath(), fileName, null);

                ExifInterface ei = new ExifInterface(fileName);
                Log.w(" TEST ", " TAG_GPS_LATITUDE= " + ei.getAttributeDouble(ei.TAG_GPS_LATITUDE, 0.0));
                Log.w(" TEST ", " TAG_GPS_LONGITUDE= " + ei.getAttribute(ei.TAG_GPS_LONGITUDE));


            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 发送广播，通知刷新图库的显示
        this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + fileName)));
    }

    /**
     * 拍照
     */
    private void takePicture() {
        if (mCameraDevice == null) return;
        // 创建拍照需要的CaptureRequest.Builder
        final CaptureRequest.Builder captureRequestBuilder;
        try {
            captureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
            // 将imageReader的surface作为CaptureRequest.Builder的目标
            captureRequestBuilder.addTarget(mImageReader.getSurface());
//            // 自动对焦
            captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, mPreviewCaptureRequest.get(CaptureRequest.CONTROL_AF_MODE));
//            mPreviewCaptureRequest.get(CaptureRequest.CONTROL_AF_MODE);
//            // 自动曝光
            captureRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, mPreviewCaptureRequest.get(CaptureRequest.CONTROL_AE_MODE));
//            mPreviewCaptureRequest.get(CaptureRequest.CONTROL_AE_MODE);
            //白平衡
            captureRequestBuilder.set(CaptureRequest.CONTROL_AWB_MODE, mPreviewCaptureRequest.get(CaptureRequest.CONTROL_AWB_MODE));
//            mPreviewCaptureRequest.get(CaptureRequest.CONTROL_AWB_MODE);
            // 获取手机方向
            int rotation = getWindowManager().getDefaultDisplay().getRotation();
            // 根据设备方向计算设置照片的方向
            captureRequestBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
            //拍照
            CaptureRequest mCaptureRequest = captureRequestBuilder.build();
            mCameraCaptureSession.capture(mCaptureRequest, mSessionCaptureCallback, mChildHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }


    //延时
    private class Sleep implements Runnable {

        private int num;
        private boolean flag = false;//标志

        public Sleep(int num) {
            this.num = num;
        }


        @Override
        public void run() {
            flag = true;
            num = num * 1000;
            try {
                Thread.sleep(num);
//                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        public boolean getFlag() {
            return flag;
        }

    }


    @Override
    public void onClick(View v) {
        FlashStrategy strategy = null;
        FlashStrategy wbstr = null;
        switch (v.getId()) {
            case R.id.tv_flash_close:
                strategy = new CloseStrategy();
                tv_flashStatus.setText("关闭");
                break;
            case R.id.tv_flash_auto:
                tv_flashStatus.setText("自动");
                strategy = new AutoStrategy();
                break;
            case R.id.tv_flash_open:
                tv_flashStatus.setText("打开");
                strategy = new OpenStrategy();
                break;
            case R.id.tv_flash_keep_open:
                tv_flashStatus.setText("常亮");
                strategy = new KeepOpenStrategy();
                break;
            case R.id.iv_wb_auto:
                wbstr = new AutoWBStrategy();
                break;
            case R.id.iv_wb_cloudy:
                wbstr = new CloudyWBStrategy();
                break;
            case R.id.iv_wb_daylight:
                wbstr = new DaylightWBStrategy();
                break;
            case R.id.iv_wb_fluore:
                wbstr = new FluoreWBStrategy();
                break;
            case R.id.iv_wb_incande:
                wbstr = new IncandeWBStrategy();
                break;
            case R.id.iv_wb_shade:
                wbstr = new ShadeWBStrategy();
                break;
            case R.id.iv_wb_twilight:
                wbstr = new TwilightWBStrategy();
                break;
            case R.id.iv_wb_warm:
                wbstr = new WarmWBStrategy();
                break;
        }
        //说明点击了文字 切换闪光灯
        if (strategy != null) {
            //重新设置背景颜色
            clearAllFlashTextBackground(v.getId());
            //消失动画
            closeFlashLayout();
            //重新设置闪光灯
            strategy.setCaptureRequest(mPreviewCaptureRequest, mCameraCaptureSession, mChildHandler);
        }
        if (wbstr != null) {
            wbstr.setCaptureRequest(mPreviewCaptureRequest, mCameraCaptureSession, mChildHandler);
        }

    }

    public void closeFlashLayout() {
        Animation anim = AnimationUtils.loadAnimation(this, R.anim.flash_out);
        mFlashLayout.setAnimation(anim);
        mFlashLayout.setVisibility(View.GONE);
    }

    public void clearAllFlashTextBackground(int id) {
        tv_flashClose.setBackground(null);
        tv_flashOpen.setBackground(null);
        tv_flashKeepOpen.setBackground(null);
        tv_flashAuto.setBackground(null);
        findViewById(id).setBackground(getResources().getDrawable(R.drawable.flash_text_shape));
    }


    /**
     * 初始化TextureView的纹理生成监听，只有纹理生成准备好了。我们才能去进行摄像头的初始化工作让TextureView接收摄像头预览画面
     */
    private void initTextureViewStateListener() {
        mTextureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
                //可以使用纹理
//                checkPermission();
                initCameraManager();
                selectCamera();
                openCamera();

            }

            @Override
            public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
                //纹理尺寸变化

            }

            @Override
            public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
                //纹理被销毁
                //SurfaceView销毁
                // 释放Camera资源
                if (null != mCameraDevice) {
                    mCameraDevice.close();
                    mCameraDevice = null;
                }
                if (null != mMediaRecorder)
                    mMediaRecorder = null;
                return false;
            }

            @Override
            public void onSurfaceTextureUpdated(SurfaceTexture surface) {
                //纹理更新

            }
        });
    }

    /**
     * 初始化子线程Handler，操作Camera2需要一个子线程的Handler
     */
    private void initChildHandler() {
        HandlerThread handlerThread = new HandlerThread("Camera2Demo");
        handlerThread.start();
        mChildHandler = new Handler(handlerThread.getLooper());
        mainHandler = new Handler(getMainLooper());
    }

    /**
     * 初始化MediaRecorder
     */
    private void initMediaRecorder() {
        mMediaRecorder = new MediaRecorder();
    }

    /*
     * 创建文件名，文件名为当前日期
     */
    public File voidename() {
        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        jpegName = format.format(new Date()) + ".mp4";
        String fileName;
        File file;
        if (Build.BRAND.equals("Xiaomi")) { // 小米手机
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + jpegName;
        } else { // Meizu 、Oppo
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/" + jpegName;
            Log.d(TAG,fileName);
        }
        file = new File(fileName);
        if (file.exists()) {
            file.delete();
        }
        // 发送广播，通知刷新图库的显示
//        this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + jpegName)));
        return file;


//        try {
//            FileOutputStream out = new FileOutputStream(file);
//            out.flush();
//            out.close();
//// 插入图库
//            MediaStore.Images.Media.insertImage(this.getContentResolver(), file.getAbsolutePath(), fileName, null);
//
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

    }


    /**
     * 配置录制视频相关数据
     */
    private void configMediaRecorder() {

//        File file = new File(getExternalCacheDir(), "demo.mp4");
        voidefile = voidename();
        if (voidefile.exists()) {
            voidefile.delete();
        }
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);//设置音频来源
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);//设置视频来源
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);//设置输出格式
        mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);//设置音频编码格式，请注意这里使用默认，实际app项目需要考虑兼容问题，应该选择AAC
        mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);//设置视频编码格式，请注意这里使用默认，实际app项目需要考虑兼容问题，应该选择H264
        mMediaRecorder.setVideoEncodingBitRate(8 * 1024 * 1920);//设置比特率 一般是 1*分辨率 到 10*分辨率 之间波动。比特率越大视频越清晰但是视频文件也越大。
        mMediaRecorder.setVideoFrameRate(30);//设置帧数 选择 30即可， 过大帧数也会让视频文件更大当然也会更流畅，但是没有多少实际提升。人眼极限也就30帧了。
        Size size = getMatchingSize2();
        mMediaRecorder.setVideoSize(size.getWidth(), size.getHeight());
        mMediaRecorder.setOrientationHint(90);
        Surface surface = new Surface(mTextureView.getSurfaceTexture());
        mMediaRecorder.setPreviewDisplay(surface);

        mMediaRecorder.setOutputFile(voidefile.getAbsolutePath());
        try {
             mMediaRecorder.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * 重新配置录制视频时的CameraCaptureSession
     */
    private void config() {
        try {
            mCameraCaptureSession.stopRepeating();//停止预览，准备切换到录制视频
            mCameraCaptureSession.close();//关闭预览的会话，需要重新创建录制视频的会话
            mCameraCaptureSession = null;
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
        configMediaRecorder();
        Size cameraSize = getMatchingSize2();
        SurfaceTexture surfaceTexture = mTextureView.getSurfaceTexture();
        surfaceTexture.setDefaultBufferSize(cameraSize.getWidth(), cameraSize.getHeight());
        Surface previewSurface = new Surface(surfaceTexture);
        Surface recorderSurface = mMediaRecorder.getSurface();//从获取录制视频需要的Surface
        try {
            mPreviewCaptureRequest = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            mPreviewCaptureRequest.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
            mPreviewCaptureRequest.addTarget(previewSurface);
            mPreviewCaptureRequest.addTarget(recorderSurface);
            //请注意这里设置了Arrays.asList(previewSurface,recorderSurface) 2个Surface，很好理解录制视频也需要有画面预览，第一个是预览的Surface，第二个是录制视频使用的Surface
            mCameraDevice.createCaptureSession(Arrays.asList(previewSurface, recorderSurface), new CameraCaptureSession.StateCallback() {
                @Override
                public void onConfigured(@NonNull CameraCaptureSession session) {
                    mCameraCaptureSession = session;
                    try {
                        // 自动对焦
                        mPreviewCaptureRequest.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
                        // 打开闪光灯
                        mPreviewCaptureRequest.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
                        //自动白平衡
//                        mPreviewCaptureRequest.set(CaptureRequest.CONTROL_AWB_MODE, mPreviewCaptureRequest.get(CaptureRequest.CONTROL_AWB_MODE));
                        //执行重复获取数据请求，等于一直获取数据呈现预览画面，mSessionCaptureCallback会返回此次操作的信息回调
                        mCameraCaptureSession.setRepeatingRequest(mPreviewCaptureRequest.build(), new CameraCaptureSession.CaptureCallback() {
                            @Override
                            public void onCaptureStarted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, long timestamp, long frameNumber) {
                                super.onCaptureStarted(session, request, timestamp, frameNumber);
                            }

                            @Override
                            public void onCaptureProgressed(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull CaptureResult partialResult) {
                                super.onCaptureProgressed(session, request, partialResult);
                            }

                            @Override
                            public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
                                CameraActivity.this.onCameraImagePreviewed(result);
                            }

                            @Override
                            public void onCaptureFailed(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull CaptureFailure failure) {
                                super.onCaptureFailed(session, request, failure);
                            }
                        }, mChildHandler);
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession session) {
                    Toast.makeText(CameraActivity.this, "配置失败", Toast.LENGTH_SHORT).show();
                }
            }, mChildHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }



    }

    /**
     * 开始录制视频
     */
    private void startRecorder() {
        mMediaRecorder.start();


    }

    /**
     * 暂停录制视频（暂停后视频文件会自动保存）
     */
    private void stopRecorder() {
        mMediaRecorder.stop();
        mMediaRecorder.reset();
        // 发送广播，通知刷新图库的显示
//        this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + jpegName)));
    }

    /**
     * 初始化Camera2的相机管理，CameraManager用于获取摄像头分辨率，摄像头方向，摄像头id与打开摄像头的工作
     */
    private void initCameraManager() {
        mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

    }

    /**
     * 选择一颗我们需要使用的摄像头，主要是选择使用前摄还是后摄或者是外接摄像头
     */
    private void selectCamera() {
        if (mCameraManager != null) {
            Log.e(TAG, "selectCamera: CameraManager is null");

        }
        try {
            String[] cameraIdList = mCameraManager.getCameraIdList();   //获取当前设备的全部摄像头id集合
            if (cameraIdList.length == 0) {
                Log.e(TAG, "selectCamera: cameraIdList length is 0");
            }
            for (String cameraId : cameraIdList) { //遍历所有摄像头
                CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(cameraId);//得到当前id的摄像头描述特征
                Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING); //获取摄像头的方向特征信息
                if (facing == CameraCharacteristics.LENS_FACING_BACK) { //这里选择了后摄像头
                    mCurrentSelectCamera = cameraId;

                }
            }

        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    private void initCameraDeviceStateCallback() {
        mCameraDeviceStateCallback = new CameraDevice.StateCallback() {
            @Override
            public void onOpened(@NonNull CameraDevice camera) {
                //摄像头被打开
                try {
                    mCameraDevice = camera;
                    cameraSize = getMatchingSize2();//计算获取需要的摄像头分辨率
//                    CameraActivity.this.runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            mTextureView.setAspectRation(cameraSize.getWidth(),cameraSize.getHeight());
//                            mdrView.setAspectRation(cameraSize.getWidth(),cameraSize.getHeight());
//                        }
//                    });

                    SurfaceTexture surfaceTexture = mTextureView.getSurfaceTexture();//得到纹理
                    surfaceTexture.setDefaultBufferSize(cameraSize.getWidth(), cameraSize.getHeight());
                    Surface previewSurface = new Surface(surfaceTexture);

                    mPreviewCaptureRequest = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
                    //自动聚焦
                    mPreviewCaptureRequest.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
                    // 自动曝光
                    mPreviewCaptureRequest.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
                    //自动白平衡
                    mPreviewCaptureRequest.set(CaptureRequest.CONTROL_AWB_MODE, CaptureRequest.CONTROL_AWB_MODE_AUTO);
                    mPreviewCaptureRequest.addTarget(previewSurface);
                    mPreviewCaptureRequest.set(CaptureRequest.STATISTICS_FACE_DETECT_MODE, getFaceDetectMode());//设置人脸检查模式
                    mCameraDevice.createCaptureSession(Arrays.asList(previewSurface, mImageReader.getSurface()), mSessionStateCallback, mChildHandler);//创建数据捕获会话，用于摄像头画面预览，这里需要等待mSessionStateCallback回调
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onDisconnected(@NonNull CameraDevice camera) {
                //摄像头断开

            }

            @Override
            public void onError(@NonNull CameraDevice camera, int error) {
                //异常

            }
        };
    }

    private void initTakePhoto() {
        mImageReader = ImageReader.newInstance(1080, 1920, ImageFormat.JPEG, 1);
        mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() { //可以在这里处理拍照得到的临时照片 例如，写入本地
            @Override
            public void onImageAvailable(ImageReader reader) {
//                mCameraDevice.close();
//                mSurfaceView.setVisibility(View.INVISIBLE);
                // 拿到拍照照片数据
                Image image = reader.acquireNextImage();
                ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                byte[] bytes = new byte[buffer.remaining()];
                buffer.get(bytes);//由缓冲区存入字节数组
                //保存

                Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

                if (bitmap != null) {
                    if (mCameraID == FRONT_CAMERA) {
                        //前置摄像头拍的要先旋转180度
                        bitmap = adjustPhotoRotation(bitmap, 180);
                    } else if (Build.VERSION.SDK_INT <= 28) {
                        if (mCameraID == BACK_CAMERA)
                            bitmap = adjustPhotoRotation(bitmap, 90);
                    }
                    iv_thumb.setImageBitmap(bitmap);
                    DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                    jpegName = format.format(new Date()) + ".JPEG";
                    saveBitmap(bitmap, jpegName);
                }

                image.close();
            }
        }, mainHandler);

    }

    Bitmap adjustPhotoRotation(Bitmap bm, final int orientationDegree) {
        Matrix m = new Matrix();
        m.setRotate(orientationDegree, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);

        try {
            Bitmap bm1 = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), m, true);
            return bm1;
        } catch (OutOfMemoryError ex) {
        }
        return null;
    }

    private void initSessionStateCallback() {
        mSessionStateCallback = new CameraCaptureSession.StateCallback() {
            @Override
            public void onConfigured(@NonNull CameraCaptureSession session) {
                mCameraCaptureSession = session;
                try {
                    // 自动对焦
                    mPreviewCaptureRequest.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
                    // 打开闪光灯
                    mPreviewCaptureRequest.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
                    //自动白平衡
                    mPreviewCaptureRequest.set(CaptureRequest.CONTROL_AWB_MODE, CaptureRequest.CONTROL_AWB_MODE_AUTO);
                    //执行重复获取数据请求，等于一直获取数据呈现预览画面，mSessionCaptureCallback会返回此次操作的信息回调
                    mCameraCaptureSession.setRepeatingRequest(mPreviewCaptureRequest.build(), mSessionCaptureCallback, mChildHandler);
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onConfigureFailed(@NonNull CameraCaptureSession session) {
                Toast.makeText(CameraActivity.this, "配置失败", Toast.LENGTH_SHORT).show();
            }
        };
    }

    private void initSessionCaptureCallback() {
        mSessionCaptureCallback = new CameraCaptureSession.CaptureCallback() {
            @Override
            public void onCaptureStarted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, long timestamp, long frameNumber) {
                super.onCaptureStarted(session, request, timestamp, frameNumber);
            }

            @Override
            public void onCaptureProgressed(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull CaptureResult partialResult) {
                super.onCaptureProgressed(session, request, partialResult);
            }

            @Override
            public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
                CameraActivity.this.onCameraImagePreviewed(result);
            }

            @Override
            public void onCaptureFailed(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull CaptureFailure failure) {
                super.onCaptureFailed(session, request, failure);
            }
        };
    }

    /**
     * 打开摄像头，这里打开摄像头后，我们需要等待mCameraDeviceStateCallback的回调
     */
    @SuppressLint("MissingPermission")
    private void openCamera() {
        try {
            mCameraManager.openCamera(mCurrentSelectCamera, mCameraDeviceStateCallback, mChildHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取支持的最高人脸检测级别
     *
     * @return
     */
    private int getFaceDetectMode() {
        if (faceDetectModes == null) {
            return CaptureRequest.STATISTICS_FACE_DETECT_MODE_FULL;
        } else {
            return faceDetectModes[faceDetectModes.length - 1];
        }
    }

    /**
     * 计算需要的使用的摄像头分辨率
     *
     * @return
     */
    private Size getMatchingSize2() {
        Size selectSize = null;
        try {
            CameraCharacteristics cameraCharacteristics = mCameraManager.getCameraCharacteristics(mCurrentSelectCamera);
            StreamConfigurationMap streamConfigurationMap = cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
            Size[] sizes = streamConfigurationMap.getOutputSizes(ImageFormat.JPEG);

            //可用于判断是否支持人脸检测，以及支持到哪种程度
            faceDetectModes = cameraCharacteristics.get(CameraCharacteristics.STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES);//支持的人脸检测模式
            int maxFaceCount = cameraCharacteristics.get(CameraCharacteristics.STATISTICS_INFO_MAX_FACE_COUNT);//支持的最大检测人脸数量


            DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); //因为我这里是将预览铺满屏幕,所以直接获取屏幕分辨率
            int deviceWidth = displayMetrics.widthPixels; //屏幕分辨率宽
            int deviceHeigh = displayMetrics.heightPixels; //屏幕分辨率高
            Log.e(TAG, "getMatchingSize2: 屏幕密度宽度=" + deviceWidth);
            Log.e(TAG, "getMatchingSize2: 屏幕密度高度=" + deviceHeigh);
            /**
             * 循环40次,让宽度范围从最小逐步增加,找到最符合屏幕宽度的分辨率,
             * 你要是不放心那就增加循环,肯定会找到一个分辨率,不会出现此方法返回一个null的Size的情况
             * ,但是循环越大后获取的分辨率就越不匹配
             */
            for (int j = 1; j < 41; j++) {
                for (int i = 0; i < sizes.length; i++) { //遍历所有Size
                    Size itemSize = sizes[i];
                    Log.e(TAG, "当前itemSize 宽=" + itemSize.getWidth() + "高=" + itemSize.getHeight());
                    //判断当前Size高度小于屏幕宽度+j*5  &&  判断当前Size高度大于屏幕宽度-j*5  &&  判断当前Size宽度小于当前屏幕高度
                    if (itemSize.getHeight() < (deviceWidth + j * 5) && itemSize.getHeight() > (deviceWidth - j * 5)) {
                        if (selectSize != null) { //如果之前已经找到一个匹配的宽度
                            if (Math.abs(deviceHeigh - itemSize.getWidth()) < Math.abs(deviceHeigh - selectSize.getWidth())) { //求绝对值算出最接近设备高度的尺寸
                                selectSize = itemSize;
                                continue;
                            }
                        } else {
                            selectSize = itemSize;
                        }

                    }
                }
                if (selectSize != null) { //如果不等于null 说明已经找到了 跳出循环
                    break;
                }
            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
        Log.e(TAG, "getMatchingSize2: 选择的分辨率宽度=" + selectSize.getWidth());
        Log.e(TAG, "getMatchingSize2: 选择的分辨率高度=" + selectSize.getHeight());
        return selectSize;
    }


    /**
     * 处理相机画面处理完成事件，获取检测到的人脸坐标，换算并绘制方框
     *
     * @param result
     */
    @SuppressLint("ShowToast")
    private void onCameraImagePreviewed(CaptureResult result) {
        Face faces[] = result.get(CaptureResult.STATISTICS_FACES);
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mdrView.setAspectRation(cameraSize.getWidth(), cameraSize.getHeight());
            }
        });
        Toast.makeText(this, "人脸个数:[\"+faces.length+\"]", Toast.LENGTH_SHORT);
//        showMessage(false,"人脸个数:["+faces.length+"]");
        Canvas canvas = mdrView.lockCanvas();
        canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);//旧画面清理覆盖

        if (faces.length > 0) {
            for (int i = 0; i < faces.length; i++) {
                Rect fRect = faces[i].getBounds();
                Log("[R" + i + "]:[left:" + fRect.left + ",top:" + fRect.top + ",right:" + fRect.right + ",bottom:" + fRect.bottom + "]");
//                showMessage(true,"[R"+i+"]:[left:"+fRect.left+",top:"+fRect.top+",right:"+fRect.right+",bottom:"+fRect.bottom+"]");

                //人脸检测坐标基于相机成像画面尺寸以及坐标原点。此处进行比例换算
                //成像画面与方框绘制画布长宽比比例（同画面角度情况下的长宽比例（此处前后摄像头成像画面相对预览画面倒置（±90°），计算比例时长宽互换））
                float scaleWidth = canvas.getHeight() * 1.0f / cameraSize.getWidth();
                float scaleHeight = canvas.getWidth() * 1.0f / cameraSize.getHeight();

                //坐标缩放
                int l = (int) (fRect.left * scaleWidth);
                int t = (int) (fRect.top * scaleHeight);
                int r = (int) (fRect.right * scaleWidth);
                int b = (int) (fRect.bottom * scaleHeight);
                Log("[T" + i + "]:[left:" + l + ",top:" + t + ",right:" + r + ",bottom:" + b + "]");
//                showMessage(true,"[T"+i+"]:[left:"+l+",top:"+t+",right:"+r+",bottom:"+b+"]");

                //人脸检测坐标基于相机成像画面尺寸以及坐标原点。此处进行坐标转换以及原点(0,0)换算
                //人脸检测：坐标原点为相机成像画面的左上角，left、top、bottom、right以成像画面左上下右为基准
                //画面旋转后：原点位置不一样，根据相机成像画面的旋转角度需要换算到画布的左上角，left、top、bottom、right基准也与原先不一样，
                //如相对预览画面相机成像画面角度为90°那么成像画面坐标的top，在预览画面就为left。如果再翻转，那成像画面的top就为预览画面的right，且坐标起点为右，需要换算到左边
                if (mCameraID == 1) {
                    //此处前置摄像头成像画面相对于预览画面顺时针90°+翻转。left、top、bottom、right变为bottom、right、top、left，并且由于坐标原点由左上角变为右下角，X,Y方向都要进行坐标换算
                    canvas.drawRect(canvas.getWidth() - b, canvas.getHeight() - r, canvas.getWidth() - t, canvas.getHeight() - l, getPaint());
//                    canvas.drawRect(canvas.getWidth()-b,canvas.getHeight()-r,canvas.getWidth()-t,canvas.getHeight()-l,getPaint());
                } else {
                    //此处后置摄像头成像画面相对于预览画面顺时针270°，left、top、bottom、right变为bottom、left、top、right，并且由于坐标原点由左上角变为左下角，Y方向需要进行坐标换算
                    canvas.drawRect(canvas.getWidth() - b, l, canvas.getWidth() - t, r, getPaint());
//                    canvas.drawRect(canvas.getWidth()-b,l,canvas.getWidth()-t,r,getPaint());
                }
            }
        }
        mdrView.unlockCanvasAndPost(canvas);
    }

    /**
     * 初始化画笔
     */
    private Paint getPaint() {
        if (pb == null) {
            pb = new Paint();
            pb.setColor(Color.BLUE);
            pb.setStrokeWidth(10);
            pb.setStyle(Paint.Style.STROKE);//使绘制的矩形中空
        }
        return pb;
    }

    private void showMessage(final boolean add, final String message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (add) {
                    textView.setText(textView.getText() + "\n" + message);
                } else {
                    textView.setText(message);
                }
            }
        });
    }


}
